<script setup>
import {onMounted, ref, watch} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {useStore} from 'vuex';
import api, {iget, iput} from "@/api";

const store = useStore();
const users = ref([]);
const loading = ref(false);
const exportDialogVisible = ref(false);
const editAcademicDialogVisible = ref(false)
const recentDeleteDialogVisible = ref(false)
const editUserDialogVisible = ref(false)
const editAcademicForm = ref({})
const editUserForm = ref({})
const exportFields = ref([
  {label: '工号', value: 'id', checked: true, width: '120px'},
  {label: '姓名', value: 'name', checked: true, width: '70px'},
  {label: '性别', value: 'gender', checked: true, width: '58px'},
  {label: '就职状态', value: 'employmentStatus', checked: true, width: '60px'},
  {label: '学历', value: 'education', checked: true, width: '95px'},
  {label: '最高学位', value: 'highestDegree', checked: true, width: '60px'},
  {label: '职称', value: 'professionalTitle', checked: true, width: '60px'},
  {label: '手机', value: 'phone', checked: true, width: '140px'},
  {label: '身份', value: 'shenfen', checked: true, width: '60px'},
  {label: '教授专业', value: 'majorName', checked: true, width: '80px'},
  {label: '专业任教时间', value: 'teachingYears', checked: true, width: '70px'},
  {label: '国籍', value: 'nationality', checked: true, width: '60px'},
  {label: '是否实验技术人员', value: 'isLabTech', checked: true, width: '90px'},
  {label: '是否双师双能型', value: 'isDoubleQualified', checked: true, width: '90px'},
  {label: '是否工程背景', value: 'hasEngineeringBg', checked: true, width: '60px'},
  {label: '是否行业背景', value: 'hasIndustryBg', checked: true, width: '60px'},
  {label: '境外一年以上经历', value: 'hasOverseasExp', checked: true, width: '90px'},
  {label: '是否课程思政优秀教师', value: 'isOutstandingIdeological', checked: true, width: '90px'},
  {label: '学缘关系', value: 'academicOrigin', checked: true, width: '140px'},
  // {label: '序号', value: 'serialNumber', checked: true, width: '60px'},
  {label: '紧急联系人', value: 'emergencyContacts', checked: true, width: '90px'},
  {label: '紧急联系人联系方式', value: 'emergencyPhone', checked: true, width: '160px'},
  {label: '身份证号', value: 'idcard', checked: true, width: '170px'},

])

const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const fetchUsers = async () => {
  loading.value = true;
  await store.dispatch('fetchUsers');
  users.value = store.getters.users;
  total.value = store.getters.userPageInfo.total;
  loading.value = false;
};
const recentDelete = async () => {
  loading.value = true;
  await store.dispatch('fetchUsersRecentDelete');
  recentDeleteDialogVisible.value = true;
  loading.value = false;
}

const handleRestore = async (index, row) => {
  try {
    await ElMessageBox.confirm('确定要恢复该用户吗？', '提示', {
      type: 'warning'
    })
    await iget('/user/redoDeleteUserById', {id: row.id})
    ElMessage.success('恢复成功')
    await store.dispatch('fetchUsersRecentDelete')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('恢复失败')
    }
  }
}

const handlePageChange = (page) => {
  currentPage.value = page;
  store.commit('setUserPageInfo', {currentPage: page, pageSize: pageSize.value, total: total.value});
  fetchUsers();
};

const handleDelete = async (index, row) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      type: 'warning'
    })
    await api.delete('/user/deleteUserById', {params: {id: row.id}})
    users.value.splice(index, 1)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}


const addDialogVisible = ref(false)
const newUser = ref({
  id: '',
  name: '',
})

const handleAdd = () => {
  newUser.value = {id: '', name: ''}
  addDialogVisible.value = true
}

const confirmAdd = async () => {
  try {
    await api.post('/user/addUser', newUser.value)
    ElMessage.success('新增用户成功')
    addDialogVisible.value = false
    await fetchUsers()
  } catch (error) {
    ElMessage.error('新增用户失败')
  }
}

const cancelAdd = () => {
  addDialogVisible.value = false
}

const handleExportBasicInfo = () => {
  exportDialogVisible.value = true
}

const handleExportAcademicInfo = () => {
  const exportWithRetry = async (retryCount = 2) => {
    try {
      ElMessage.success('正在导出学缘信息...')
      const response = await api.get('/export/academicOriginInfo', {
        responseType: 'blob'
      })
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', '学缘信息.xlsx');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      if (retryCount > 0) {
        await exportWithRetry(retryCount - 1);
      } else {
        console.error('导出学缘信息失败,' + error);
        ElMessage.error('网络不稳定，下载中断');
      }
    }
  }
  exportWithRetry();
}

const selectedExportFields = ref(['id', 'gender', 'status', 'highest_education', 'title', 'major'])

const confirmExport = () => {
  const exportWithRetry = async (retryCount = 2) => {
    try {
      ElMessage.success('正在导出基础信息...')
      const selectedFields = exportFields.value.filter(field => selectedExportFields.value.includes(field.value)).map(field => field.value);
      const response = await api.get('/export/selectedFields', {
        params: {fields: selectedFields.join(',')},
        responseType: 'blob'
      })
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', '教师基础信息.xlsx');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      if (retryCount > 0) {
        await exportWithRetry(retryCount - 1);
      } else {
        console.error('导出失败,' + error);
        ElMessage.error('导出失败');
      }
    }
  }
  exportWithRetry();
  exportDialogVisible.value = false;
}

const cancelExport = () => {
  exportDialogVisible.value = false
}

const handleResetPassword = async (index, row) => {
  try {
    await ElMessageBox.confirm('确定要重置该用户的密码吗？', '提示', {
      type: 'warning'
    })
    await api.get('/user/resetPassword', {params: {username: row.id}})
    ElMessage.success('重置密码成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('重置密码失败')
    }
  }
}

const handleSelectAll = () => {
  if (selectedExportFields.value.length === exportFields.value.length) {
    selectedExportFields.value = [];
  } else {
    selectedExportFields.value = exportFields.value.map(field => field.value);
  }
};

const handleEditUserInfo = (index, row) => {
  editUserDialogVisible.value = true;
  editUserForm.value = {...row};
};

const handleEditAcademicInfo = async (index, row) => {
  try {
    const res = await iget('/academicOrigin/getAcademicOriginById', {id: row.id});
    if (res.data.code === 200) {
      editAcademicForm.value = {...res.data.result};
      editAcademicDialogVisible.value = true;
    } else {
      ElMessage.error('获取学缘信息失败');
    }
  } catch (error) {
    ElMessage.error('获取学缘信息失败');
  }
};

const confirmEditUser = async () => {
  try {
    await iput('/user/updateUser', editUserForm.value);
    editUserDialogVisible.value = false;
    ElMessage.success('用户信息修改成功');
    await fetchUsers();
  } catch (error) {
    ElMessage.error('用户信息修改失败');
  }
};

const confirmEditAcademic = async () => {
  try {
    const res = await iput('/academicOrigin/updateAcademicOrigin', editAcademicForm.value);
    if (res.data.code === 200) {
      editAcademicDialogVisible.value = false;
      ElMessage.success('学缘信息修改成功');
      await fetchUsers();
    } else {
      ElMessage.error('学缘信息修改失败');
    }
  } catch (error) {
    ElMessage.error('学缘信息修改失败');
  }
};

onMounted(() => {
  fetchUsers()
})

const employmentStatusOptions = [
  {label: '在职', value: '在职'},
  {label: '退休返聘', value: '退休返聘'},
  {label: '离职', value: '离职'}
]

const educationOptions = [
  {label: '大学专科', value: '大学专科'},
  {label: '大学本科', value: '大学本科'},
  {label: '硕士研究生', value: '硕士研究生'},
  {label: '博士研究生', value: '博士研究生'}
]

const highestDegreeOptions = [
  {label: '学士', value: '学士'},
  {label: '硕士', value: '硕士'},
  {label: '博士', value: '博士'}
]

const academicOriginOptions = [
  {label: '本校', value: '本校'},
  {label: '外校（境内）', value: '外校（境内）'},
  {label: '外校（境外）', value: '外校（境外）'}
]

const searchKeyword = ref('')
const searchInput = ref(null)

// 防抖搜索函数
const debounceSearch = debounce(async (keyword) => {
  if (keyword.trim() === '') {
    await fetchUsers()
    return
  }
  try {
    loading.value = true
    const res = await api.get('/user/searchUser', {
      params: {
        keyword: keyword,
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
    })
    users.value = res.data.result.records
    total.value = res.data.result.total
  } catch (error) {
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}, 300)

// 清空搜索
const clearSearch = () => {
  searchKeyword.value = ''
  ElMessage.success('已清空输入')
  debounceSearch('')
}

// 防抖函数
function debounce(fn, delay) {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 监听搜索关键词变化
watch(searchKeyword, (newVal) => {
  debounceSearch(newVal)
})
</script>

<template>
  <el-card>
    <div style="display: flex; justify-content: space-between; margin-bottom: 20px;">
      <div style="display: flex; gap: 2vw;">
        <el-button size="small" type="primary" @click="handleAdd">新增用户</el-button>
        <el-input
            ref="searchInput"
            v-model="searchKeyword"
            clearable
            placeholder="输入姓名或者工号模糊搜索"
            size="small"
            style="width: 260px"
            @clear="clearSearch"
        >
          <template #append>
            <el-button size="small" @click="debounceSearch(searchKeyword)">搜索</el-button>
          </template>
        </el-input>
      </div>
      <div>
        <el-button size="small" type="primary" @click="recentDelete">最近删除</el-button>
        <el-button size="small" type="success" @click="handleExportBasicInfo">导出基础信息</el-button>
        <el-button size="small" type="success" @click="handleExportAcademicInfo">导出学缘信息</el-button>
        <!--        <el-button size="small" type="success" @click="handleExportResearchInfo">导出科研信息</el-button>-->
      </div>
    </div>
    <div class="scroll-container">
      <el-table v-loading="loading" :data="users" style="width: max-content">
        <!-- 修改1: 固定前两列 -->
        <el-table-column fixed label="姓名" prop="name" width="70px"/>
        <el-table-column fixed label="工号" prop="id" width="120px"/>
        <el-table-column v-for="field in exportFields.slice(2)" :key="field.value" :label="field.label"
                         :prop="field.value"
                         :width="field.width || 'auto'"/>
        <el-table-column label="操作" width="300px">
          <template #default="scope">
            <el-button size="small" style="color: #409EFF; font-size: 12px" type="text"
                       @click="handleResetPassword(scope.$index, scope.row)">
              重置密码
            </el-button>
            <el-button size="small" style="color: #67C23A; font-size: 12px" type="text"
                       @click="handleEditUserInfo(scope.$index, scope.row)">
              修改个人信息
            </el-button>
            <el-button size="small" style="color: #E6A23C; font-size: 12px" type="text"
                       @click="handleEditAcademicInfo(scope.$index, scope.row)">
              修改学缘信息
            </el-button>
            <el-button size="small" style="color: red; font-size: 12px" type="text"
                       @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        background
        layout="prev, pager, next"
        style="margin-top: 20px;"
        @current-change="handlePageChange"
    />
  </el-card>

  <el-dialog v-model="addDialogVisible" title="新增教师" width="30%">
    <el-form :model="newUser" label-width="80px">
      <el-form-item label="工号">
        <el-input v-model="newUser.id" placeholder="请输入工号"/>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="newUser.name" placeholder="请输入姓名"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button size="small" @click="cancelAdd">取消</el-button>
      <el-button size="small" type="primary" @click="confirmAdd">确认</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="exportDialogVisible" title="选择导出字段" width="50%">
    <div style="display: flex; flex-direction: column; max-height: 300px; overflow-y: auto;">
      <el-checkbox-group v-model="selectedExportFields">
        <el-checkbox v-for="field in exportFields" :key="field.value" :label="field.value">{{
            field.label
          }}
        </el-checkbox>
      </el-checkbox-group>
    </div>
    <template #footer>
      <el-button size="small" style="margin-right: 30vw" type="primary" @click="handleSelectAll">全选</el-button>
      <el-button size="small" @click="cancelExport">取消</el-button>
      <el-button size="small" type="primary" @click="confirmExport">导出</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="editUserDialogVisible" title="修改个人信息" width="50%">
    <el-form :model="editUserForm" label-width="120px">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="工号">
            <el-input v-model="editUserForm.id" :disabled="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名">
            <el-input v-model="editUserForm.name"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="性别">
            <el-select v-model="editUserForm.gender" placeholder="请选择">
              <el-option label="男" value="男"/>
              <el-option label="女" value="女"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期">
            <el-date-picker
                v-model="editUserForm.birthDate"
                format="YYYY-MM"
                type="month"
                value-format="YYYY-MM"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="就职状态">
            <el-select v-model="editUserForm.employmentStatus" placeholder="请选择">
              <el-option
                  v-for="option in employmentStatusOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期">
            <el-date-picker
                v-model="editUserForm.entryDate"
                format="YYYY-MM"
                type="month"
                value-format="YYYY-MM"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="学历">
            <el-select v-model="editUserForm.education" placeholder="请选择">
              <el-option
                  v-for="option in educationOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最高学位">
            <el-select v-model="editUserForm.highestDegree" placeholder="请选择">
              <el-option
                  v-for="option in highestDegreeOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="职称">
            <el-input v-model="editUserForm.professionalTitle"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="专业类别">
            <el-input v-model="editUserForm.subjectCategory"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="教学类型">
            <el-input v-model="editUserForm.teachingType"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="专业名称">
            <el-input v-model="editUserForm.majorName"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="专业代码">
            <el-input v-model="editUserForm.majorCode"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="教学年限">
            <el-input v-model="editUserForm.teachingYears"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="政治面貌">
            <el-input v-model="editUserForm.politicalStatus"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="国籍">
            <el-input v-model="editUserForm.nationality"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="手机号">
            <el-input v-model="editUserForm.phone"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号">
            <el-input v-model="editUserForm.idcard"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="紧急联系人">
            <el-input v-model="editUserForm.emergencyContacts"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="紧急联系电话">
            <el-input v-model="editUserForm.emergencyPhone"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="学缘信息">
            <el-select v-model="editUserForm.academicOrigin" placeholder="请选择">
              <el-option
                  v-for="option in academicOriginOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="24">
          <el-form-item label="家庭住址">
            <el-input v-model="editUserForm.address"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button size="small" @click="editUserDialogVisible = false">取消</el-button>
      <el-button size="small" type="primary" @click="confirmEditUser">保存</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="editAcademicDialogVisible" title="修改学缘信息" width="50%">
    <el-form :model="editAcademicForm" label-width="120px">
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="职称等级">
            <el-input v-model="editAcademicForm.professionalLevel"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职务">
            <el-input v-model="editAcademicForm.zhiwu"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="大专院校">
            <el-input v-model="editAcademicForm.dazhuan"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="大专专业">
            <el-input v-model="editAcademicForm.dazhuanMajor"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="本科院校">
            <el-input v-model="editAcademicForm.benke"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="本科专业">
            <el-input v-model="editAcademicForm.benkeMajor"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="本科级别">
            <el-input v-model="editAcademicForm.benkeLevel"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="硕士院校">
            <el-input v-model="editAcademicForm.shuoshi"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="硕士专业">
            <el-input v-model="editAcademicForm.shuoshiMajor"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="硕士级别">
            <el-input v-model="editAcademicForm.shuoshiLevel"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="博士院校">
            <el-input v-model="editAcademicForm.phd"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="博士专业">
            <el-input v-model="editAcademicForm.phdMajor"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="博士级别">
            <el-input v-model="editAcademicForm.phdLevel"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="博士后院校">
            <el-input v-model="editAcademicForm.afterphd"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="博士后级别">
            <el-input v-model="editAcademicForm.afterphdLevel"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button size="small" @click="editAcademicDialogVisible = false">取消</el-button>
      <el-button size="small" type="primary" @click="confirmEditAcademic">保存</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="recentDeleteDialogVisible" title="最近删除" width="50vw" @closed="fetchUsers">
    <el-table
        v-loading="loading"
        :data="store.getters.recentDeleteUsers"
        empty-text="暂无数据"
        header-align="center"
    >
      <el-table-column align="center" label="工号" prop="id">
        <template #default="scope">
          <el-col :span="24">{{ scope.row.id }}</el-col>
        </template>
      </el-table-column>
      <el-table-column align="center" label="姓名" prop="name">
        <template #default="scope">
          <el-col :span="24">{{ scope.row.name }}</el-col>
        </template>
      </el-table-column>
      <el-table-column align="center" label="删除时间" prop="deleteTime" width="200">
        <template #default="scope">
          <el-col :span="28">{{ scope.row.deleteTime }}</el-col>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-col :span="24">
            <el-button
                size="small"
                style="background-color: #67C23A; border-color: #67C23A"
                type="success"
                @click="handleRestore(scope.$index, scope.row)"
            >
              恢复
            </el-button>
          </el-col>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button size="small" @click="recentDeleteDialogVisible = false; fetchUsers()">取消</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-table .el-table__fixed {
  background-color: #f5f7fa;
}

.el-table th {
  height: 40px;
}

.el-table td {
  height: 36px;
}

.el-card {
  margin: 15px;
}

.scroll-container {
  overflow-x: auto;
  width: 100%;
}

.el-table {
  min-width: 100%;
}
</style>
